package com.example.usernamee.myhandler;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
int []images={R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5};
    int x=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView imageView=(ImageView)findViewById(R.id.img);
        final Handler mHandler=new Handler(){
            /**
             * Subclasses must implement this to receive messages.
             *
             * @param msg
             */
            @Override
            public void handleMessage(Message msg) {
                if (msg.what==0X1233){//这里的0X1233是一个随意数，也可以把它改成0,1,2，。。。
                    imageView.setImageResource(images[x++ % images.length]);//若把x++ % images.length改成x++着不会循环运行
                }
                super.handleMessage(msg);

            }
        };
        //定义一个定时器，让它周期性的执行指定任务
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0X1233);
            }
        },4000,3000);//这里的4000指的是4000毫秒后发送消息，3000指的是3000毫秒后更换一张图片
    }
}
